package com.fileupload.process.strategy;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * 相同目录结构移动策略
 * 上传完成后保持原目录结构移动到目标位置
 * @author 小乙
 */
public class SameMoveFileStrategy extends AbstractFileFinishActionStrategy {
    
    public SameMoveFileStrategy() {
        super("same-move");
    }
    
    /**
     * 构造函数
     * 
     * @param monitorDir 监控目录
     */
    public SameMoveFileStrategy(String monitorDir) {
        super("same-move", monitorDir);
    }
    
    @Override
    public boolean execute(File sourceFile, String targetDir) {
        logger.debug("Moving file with same directory structure: {}", sourceFile.getAbsolutePath());
        
        if (sourceFile == null || !sourceFile.exists() || targetDir == null || targetDir.isEmpty()) {
            logger.warn("Invalid parameters for moving file");
            return false;
        }
        
        try {
            // 构建目标文件路径
            String sourceParent = sourceFile.getParent();
            String fileName = sourceFile.getName();
            
            // 创建目标目录
            Path targetDirPath = Paths.get(targetDir);
            boolean dirCreated = createDirectory(targetDir);
            if (!dirCreated) {
                return false;
            }
            
            // 移动文件到目标目录
            Path targetFilePath = targetDirPath.resolve(fileName);
            Files.move(sourceFile.toPath(), targetFilePath, StandardCopyOption.REPLACE_EXISTING);
            
            logger.info("File moved successfully: {} -> {}", 
                       sourceFile.getAbsolutePath(), targetFilePath.toString());
            return true;
            
        } catch (IOException e) {
            logger.error("Failed to move file: {}", sourceFile.getAbsolutePath(), e);
            return false;
        }
    }
}
